import $ from 'jquery'
import JSMpeg from '@cycjimmy/jsmpeg-player'
const MathUtils = {
    // map number x from range [a, b] to [c, d]
    map: (x, a, b, c, d) => ((x - a) * (d - c)) / (b - a) + c,
    // linear interpolation
    lerp: (a, b, n) => (1 - n) * a + n * b,
    transitionEvent: whichTransitionEvent()
};
function whichTransitionEvent () {
    let t
    let el = document.createElement('fakeelement')
    let transitions = {
        'transition': 'transitionend',
        'OTransition': 'oTransitionEnd',
        'MozTransition': 'transitionend',
        'WebkitTransition': 'webkitTransitionEnd',
        'MsTransition': 'msTransitionEnd'
    }
    for (t in transitions) {
        if (el.style[t] !== undefined) {
            return transitions[t]
        }
    }
}

export class Base{
    constructor(child = null) {
        this.body = document.body;
        this.version = this.getVersion();//浏览器版本
        this.shu = window.matchMedia("(orientation: portrait)").matches;//竖屏
        this.IMAGES = null;
        window.addEventListener("resize", this.calcWinsize.bind(this));
        this.calcWinsize();
        this.IsPc();
        this.uunn();
        //滚动位置更新
        this.docScroll = window.pageYOffset || document.documentElement.scrollTop;
        this.cache =0;//存储滚动位置
        this.distance = 0;//滚动偏移值
        this.hashPosition();
    }
    createScrollEvent(){
        window.addEventListener("scroll", this.getPageYScroll.bind(this));
    }
    getPageYScroll(){
        this.docScroll = window.pageYOffset || document.documentElement.scrollTop;
        this.distance = this.docScroll - this.cache;
        this.cache =this.docScroll;
        this.scrollChildFn();
    }
    //下级绑定滚动条
    scrollChildFn(){}
    //窗口宽高数据
    calcWinsize(){this.winsize = {vw: window.innerWidth, vh: window.innerHeight};}
    // 获取浏览器版本
    getVersion(){
        var explorer = window.navigator.userAgent ;
        if (explorer.indexOf("MSIE") >= 0||explorer.indexOf("Trident")>0 ) {
            if(explorer.indexOf("MSIE 5")>0||explorer.indexOf("MSIE 6")>0||explorer.indexOf("MSIE 7")>0||explorer.indexOf("MSIE 8")>0) {
                return 'LowerIEVersion';
            }else{
                return 'EdgeOrTrident';
            }
        }
        else if (explorer.indexOf("Maxthon") >= 0) {return 'Maxthon';}
        else if (explorer.indexOf("Firefox") >= 0) {return 'FireFox';}
        else if(explorer.indexOf("Chrome") >= 0){ return 'Chrome';}
        else if(explorer.indexOf("Opera") >= 0){ return 'Opera';}
        else if(explorer.indexOf("Safari") >= 0){ return 'Safari';}
    }
    //判断是否为pc端
    IsPc(){
        var self = this;
        var userAgentInfo = navigator.userAgent;
        var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
        self.isPc = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) { self.isPc = false; break; }else if(navigator.maxTouchPoints>0){
                self.isPc = false; break;
            }
        }
        self.isAndroid = userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Adr') > -1; //android终端
        self.isiOS = !!userAgentInfo.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        return self.isPc;
    }
    //获取元素距离顶部高度
    getTop(element){
        var top;
        while (element.offsetTop === void 0) {
            element = element.parentNode;
        }
        top = element.offsetTop;
        while (element = element.offsetParent) {
            top += element.offsetTop;
        }
        return top;
    }
    //跳转到指定位置
    ScrollTo(top){window.scrollTo({top:top, behavior: 'smooth'});}
    //判断当前页面
    curPage(el){
        return ($(el).length>0);
    }
    siblings(el,name){
        $(el).addClass(name).siblings().removeClass(name);
    }
    browser_check_webp() {
        try {
            return document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0;
        } catch(err) {
            return false;
        }
    }
    Viewport(e,viewIn,viewOut,offset="0%",first=false,firstFn){
        let op = {
            root: null,
            rootMargin: "0px 0px "+offset+" 0px",
            threshold: [0,1]
        };
        let myFirst=0;
        let active = 0;
        if(!e){return false;}
        if(first){
            const observer = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    let isVisible = entry.intersectionRatio > 0.0;
                    if(isVisible&&myFirst===0) {
                        myFirst = 1;
                        firstFn();
                    }else if(isVisible&&active===0){
                        active=1;
                        viewIn();
                    }else if(!isVisible&&active===1){
                        active=0;
                        viewOut();
                    }
                });
            },op);
            observer.observe(e);//对元素监听是否在可视区
        }else{
            const observer = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    let isVisible = entry.intersectionRatio > 0.0;
                    if(isVisible&&active===0){
                        active=1;
                        viewIn();
                    }else if(!isVisible&&active===1){
                        active=0;
                        viewOut();
                    }
                });
            },op);
            observer.observe(e);//对元素监听是否在可视区
        }
    }
    storage(firstFn,moreFn){
        let stor = JSON.parse(sessionStorage.getItem('key'));
        let info ={call:0};
        if(stor===null){
            info.call=1;
            sessionStorage.setItem('key',JSON.stringify(info));
            firstFn();
        }else{
            info.call=stor.call+1;
            sessionStorage.setItem('key',JSON.stringify(info));
            moreFn();
        }
    }
    moveEnd(el,fn){
        el.addEventListener(MathUtils.transitionEvent, fn, false);
    }
    uunn(){
        console.log('%cUUNN+','display:block;padding: 0 50px;line-height: 76px;background:#f00;color: #fff; font-size: 40px;border-radius: 6px;')
        console.log('Powered by %cUUNN+%c brand creative vanguard.','color:#f00;font-weight: 900;','');
        console.log('Learn more about us \nplease visit %chttp://www.uunn.cn','text-decoration: underline;');
    }
    //根据哈希值(#)定位
    hashPosition(){
        const hash = window.location.hash;
        if (hash) {
            const targetId = hash.substring(1);
            // 获取目标元素
            const targetElement = document.getElementById(targetId);
            // 如果目标元素存在，滚动到该元素的位置
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
            }
        }
    }
    //回到顶部
    toTopFn(elm){
        if(elm){
            elm.addEventListener("click",function(){
                $('html, body').animate({ scrollTop: 0 }, 1000);
            });
        }
    }
    //ts
    creatTs(el,src,auto=false,loop=false,endFn){
        let ts = new JSMpeg.VideoElement(el,src,{
            autoplay:auto,
            loop:loop,
            control:false,
            decodeFirstFrame:false,
            chunkSize:512*512,
            hooks:{
                play:()=>{
                    el.classList.add('active');
                },
            }
        },{
            audio:false,
            onEnded:()=>{
                endFn();
            },
        });
        return ts;
    }
    //[data-media]
    TsParent(){
        const that = this;
        let tsMedia=[];
        document.querySelectorAll("[data-media]").forEach((child,key)=>{
            const step = items.querySelector('.step');
            const media = items.querySelector('video');
            const elm = items.querySelector(".layer-ts");
            if(that.shu&&elm){
                const Ts = that.creatTs(elm,elm.dataset.src,false,true);
                tsMedia.push(Ts);
            }
            that.Viewport(step,function(){
                child.classList.add('active');
                if(that.shu&&elm){
                    tsMedia[key].play();
                }else{
                    media.play();
                }
            },function(){
                child.classList.remove('active');
                if(that.shu&&elm){
                    tsMedia[key].pause();
                }else{
                    media.pause();
                }
            })
        })
    }
}

